Ext.define('appfe.stockor.statist.buyinpoint.BuyinPointController', {
	extend: 'Ext.app.ViewController',
	alias: 'controller.stockor.statist.buyinpoint.BuyinPoint',
	onRender: function () {
	},
	onBoxReady: function () {
	},
	/**
	 * 点击查询按钮的查询方法
	 */
	searchFn: function (button, clickEnven) {
		var bottompagingtoolbar = this.lookup('bottompagingtoolbar');
		bottompagingtoolbar.moveFirst();//点击查询按钮, 分页状态清除, 但是这个动作会触发pageBarBeforeChange

		var myview = this.getView();
		var params = this.assembleSearchParams();
		if (params) {
			myview.store.removeAll();
			myview.store.load({
				params: params,
				callback: function (records, operation, success) {
					// console.debug(records);
				}
			});
		}
	},
	/**
	 * [pageBarBzuotianeforeChange description]
	 */
	pageBarBeforeChange: function () {
		var params = this.assembleSearchParams();
		if (params) {
			this.getView().store.getProxy().extraParams = params;
		}
	},
	/**
	 * 拼接查询参数
	 */
	assembleSearchParams: function () {
		var params = {};

		var queryKey = this.lookup('queryKey').getValue();
		var queryValue = this.lookup('queryValue').getValue();
		if (queryKey && queryValue) {
			params[queryKey] = queryValue;
		}

		var queryInfoTimeKey = this.lookup('queryInfoTimeKey').getValue();
		var startDate = this.lookup('startDate').getRawValue();
		if (startDate) {
			if (queryInfoTimeKey && queryInfoTimeKey == 'logTime') {
				params['logStartDate'] = startDate;
			} else if (queryInfoTimeKey && queryInfoTimeKey == 'pointTime') {
				params['startDate'] = startDate;
			}
		}
		var endDate = this.lookup('endDate').getRawValue();
		if (endDate) {
			if (queryInfoTimeKey && queryInfoTimeKey == 'logTime') {
				params['logEndDate'] = endDate;
			} else if (queryInfoTimeKey && queryInfoTimeKey == 'pointTime') {
				params['endDate'] = endDate;
			}
		}

		var states = this.lookup('status').getValue();
		if (states) {
			params['status'] = states;
		}
		var isValid_checkGroup = this.lookup('grade');
		if (isValid_checkGroup) {
			var checkObjArray = isValid_checkGroup.getChecked();
			var items = [];
			Ext.Array.each(checkObjArray, function (item) {
				items.push(item.name);
			});
			params["grade"] = items;
		}
		//console.debug('params', params);
		return params;
	},
	/**
	 * 
	 */
	viewCellIdRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		var stkname = record.get('name');
		var slimsymbol = record.get('slimsymbol');
		var name = record.get('name');
		var grade = record.get('grade');
		var changeTypeFmtStr = "<a title=\"查看买入点日志&#10;代码:" + slimsymbol + "&#10;名称:" + name + "\" href=\"javascript:void(0)\" onclick=\"javascript:"
			+ "Ext.getCmp('main-card-panel').getLayout().getActiveItem().fireEvent('popupLogWin','{0}','{1}','{2}','{3}')\">{0}</a>";
		return Ext.String.format(changeTypeFmtStr, value, stkname, slimsymbol, grade);
	},
	/**
	 * 
	 */
	viewCellSymbolRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		var slimsymbol = record.get('slimsymbol');
		var name = record.get('name');
		var changeTypeFmtStr = '<a title="查看雪球行情页面&#13;代码:{1}&#10;名称:{2}" href="https://xueqiu.com/S/{0}" target="_blank">{1}</a>';
		return Ext.String.format(changeTypeFmtStr, slimsymbol.toUpperCase(), slimsymbol);
	},
	/**
	 * 
	 */
	viewCellLogTclosePriceRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		var tooltipStr = Ext.String.format('开:{0}<br>收:{1}<br>高:{2}<br>低:{3}',
			Ext.util.Format.number(record.get('logTopenPrice'), '￥0.00'),
			Ext.util.Format.number(record.get('logTclosePrice'), '￥0.00'),
			Ext.util.Format.number(record.get('logThighPrice'), '￥0.00'),
			Ext.util.Format.number(record.get('logTlowPrice'), '￥0.00'));
		metaData.tdAttr = 'data-qtip="' + Ext.String.htmlEncode(tooltipStr) + '"';
		return Ext.util.Format.number(value, '￥0.00');
	},
	/**
	 * 
	 */
	viewCellTclosePriceRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		var tooltipStr = Ext.String.format('开:{0}<br>收:{1}<br>高:{2}<br>低:{3}',
			Ext.util.Format.number(record.get('topenPrice'), '￥0.00'),
			Ext.util.Format.number(record.get('tclosePrice'), '￥0.00'),
			Ext.util.Format.number(record.get('thighPrice'), '￥0.00'),
			Ext.util.Format.number(record.get('tlowPrice'), '￥0.00'));
		metaData.tdAttr = 'data-qtip="' + Ext.String.htmlEncode(tooltipStr) + '"';
		return Ext.util.Format.number(value, '￥0.00');
	},
	/**
	 * 
	 */
	viewCellLowestTlowPriceRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		var tooltipStr = Ext.String.format('开:{0}<br>收:{1}<br>高:{2}<br>低:{3}',
			Ext.util.Format.number(record.get('lowestTopenPrice'), '￥0.00'),
			Ext.util.Format.number(record.get('lowestTclosePrice'), '￥0.00'),
			Ext.util.Format.number(record.get('lowestThighPrice'), '￥0.00'),
			Ext.util.Format.number(record.get('lowestTlowPrice'), '￥0.00'));
		metaData.tdAttr = 'data-qtip="' + Ext.String.htmlEncode(tooltipStr) + '"';
		return Ext.util.Format.number(value, '￥0.00');
	},
	/**
	 * 
	 */
	viewCellProfitAmountRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		if (Ext.typeOf(value) != 'number' && Ext.Object.isEmpty(value)) {
			return value;
		}
		if (value > 0) {
			metaData.tdAttr = 'bgcolor="red"';
			metaData.tdStyle = 'color:white';
		} else if (value < 0) {
			metaData.tdAttr = 'bgcolor="green"';
			metaData.tdStyle = 'color:white';
		}
		return Ext.util.Format.number(value, '￥0.00');
	},
	/**
	 * 
	 */
	viewCellProfitRatioRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		if (Ext.typeOf(value) != 'number' && Ext.Object.isEmpty(value)) {
			return value;
		}
		if (value > 0 && value <= 0.1) {
			metaData.tdAttr = 'bgcolor="Red"';
			metaData.tdStyle = 'color:white';
		} else if (value > 0.1) {
			metaData.tdAttr = 'bgcolor="DarKRed"';
			metaData.tdStyle = 'color:white';
		} else if (value < 0) {
			metaData.tdAttr = 'bgcolor="green"';
			metaData.tdStyle = 'color:white';
		}
		return Ext.util.Format.number(value * 100, '0.00%'); /*利润率*/
	},
	viewCellBooleanRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		if (value == true) {
			metaData.tdAttr = 'bgcolor="#00A800"';
			metaData.tdStyle = 'color:white';
			return '是';
		} else {
			metaData.tdAttr = 'bgcolor="LightGrey"';
			return '否';
		}
	},
	viewCellPlainTextRender: function (value) {/** grid cell 将html特殊字符替换 */
		return Ext.util.Format.htmlEncode(value);
	},
	viewCellStatusRender: function (value, metaData, record, rowIndex, colIndex, store, view) { /**	渲染cell */
		var rtntxt;
		var slimsymbol = record.get('slimsymbol');
		var stkname = record.get('name');
		var grade = record.get('grade');
		if (value === 'NEW') {
			var tooltipStr = Ext.String.format('状态:{0}<br>代码:{1}<br>名称:{2}<br>级别:{3}', '新建', slimsymbol, stkname, grade);
			metaData.tdAttr = 'bgcolor="#00A800" data-qtip="' + Ext.String.htmlEncode(tooltipStr) + '" data-qwidth=300';
			metaData.tdStyle = 'color:white';
			rtntxt = 'NEW';
		} else if (value === 'OPEN') {
			var tooltipStr = Ext.String.format('状态:{0}<br>代码:{1}<br>名称:{2}<br>级别:{3}', '有效', slimsymbol, stkname, grade);
			metaData.tdAttr = 'bgcolor="#FF920D" data-qtip="' + Ext.String.htmlEncode(tooltipStr) + '" data-qwidth=200';
			metaData.tdStyle = 'color:white';
			rtntxt = 'OPEN';
		} else if (value === 'CLOSE') {
			var tooltipStr = Ext.String.format('状态:{0}<br>代码:{1}<br>名称:{2}<br>级别:{3}', '关闭', slimsymbol, stkname, grade);
			metaData.tdAttr = 'bgcolor="LightGrey" data-qtip="' + Ext.String.htmlEncode(tooltipStr) + '"';
			rtntxt = 'CLOSE';
		} else {
			metaData.tdAttr = 'bgcolor="red" data-qtip="未知"';
			metaData.tdStyle = 'color:white';
			rtntxt = value;
		}
		return rtntxt;
	},
	viewCellRealtimeStatusRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		//console.debug('viewCellRealtimeStatusRender-value:', value);
		var displayVal;
		if (value == null || value == '') {
			displayVal = '点击查看';
		} else if (value == 'NULL') {
			displayVal = '无买入点';
		} else {
			displayVal = value;
		}
		var stkname = record.get('name');
		var slimsymbol = record.get('slimsymbol');
		var grade = record.get('grade');
		// var realtimeStatus = record.get('realtimeStatus');
		// var realtimeInfoTime = record.get('realtimeInfoTime');
		// var realtimeTopenPrice = record.get('realtimeTopenPrice');
		// var realtimeTclosePrice = record.get('realtimeTclosePrice');
		// var realtimeThighPrice = record.get('realtimeThighPrice');
		// var realtimeTlowPrice = record.get('realtimeTlowPrice');
		// var realtimetCloseIncreaseAmount = record.get('realtimetCloseIncreaseAmount');
		// var realtimetCloseProfitRatio = record.get('realtimetCloseProfitRatio');
		// var realtimeBackoff34TermsIslowest = record.get('realtimeBackoff34TermsIslowest');
		// var realtimeBackoff55TermsIslowest = record.get('realtimeBackoff55TermsIslowest');
		// var realtimeBackoff89TermsIslowest = record.get('realtimeBackoff89TermsIslowest');
		// var realtimeBackoff144TermsIslowest = record.get('realtimeBackoff144TermsIslowest');
		if (value === 'NEW') {
			metaData.tdAttr = 'bgcolor="#00A800"';
			metaData.tdStyle = 'color:white';
		} else if (value === 'OPEN') {
			metaData.tdAttr = 'bgcolor="#FF920D"';
			metaData.tdStyle = 'color:white';
		} else if (value === 'CLOSE') {
			metaData.tdAttr = 'bgcolor="LightGrey"';
		} else if (value === 'NULL') {
			metaData.tdAttr = 'bgcolor="Grey"';
		}
		var changeTypeFmtStr = "<a title=\"显示实时价格加入K线后的买入点分析"
			+ "&#10;------------------"
			+ "&#10;代码:" + slimsymbol
			+ "&#10;名称:" + stkname
			+ "&#10;级别:" + grade
			+ ((value === 'NEW' || value === 'OPEN' || value === 'CLOSE') ?
				"&#10;状态:" + record.get('realtimeStatus')
				+ "&#10;时间:" + record.get('realtimeInfoTime')
				+ "&#10;开:" + record.get('realtimeTopenPrice')
				+ " ,收:" + record.get('realtimeTclosePrice')
				+ " ,高:" + record.get('realtimeThighPrice')
				+ " ,低:" + record.get('realtimeTlowPrice')
				+ "&#10;利润额:" + record.get('realtimetCloseIncreaseAmount')
				+ "利润率:" + record.get('realtimetCloseProfitRatio')
				+ "&#10;前溯周期最低价状态: 34:" + (record.get('realtimeBackoff34TermsIslowest') ? "■" : "□")
				+ " ,55:" + (record.get('realtimeBackoff55TermsIslowest') ? "■" : "□")
				+ " ,89:" + (record.get('realtimeBackoff89TermsIslowest') ? "■" : "□")
				+ " ,144:" + (record.get('realtimeBackoff144TermsIslowest') ? "■" : "□")
				+ "&#10;------------------"
				+ "&#10;现价时间:" + record.get('currentTime')
				+ "&#10;现价: 现" + record.get('currentPrice')
				+ " ,开:" + record.get('currentOpen')
				+ " ,高:" + record.get('currentHigh')
				+ " ,低:" + record.get('currentLow')
				: "")

			+ "\" href=\"javascript:void(0)\""
			+ " onclick=\"javascript:Ext.getCmp('main-card-panel').getLayout().getActiveItem().fireEvent('realtimeBuyinPointAnalyze',null,'{1}','{2}','{3}')\">{0}</a>";
		var val = Ext.String.format(changeTypeFmtStr, displayVal, slimsymbol, stkname, grade);
		//console.debug('viewCellRealtimeStatusRender-val:', val);
		return val;
	},

	viewCellCurrentPriceRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		if (Ext.Object.isEmpty(value)) {
			return value;
		}
		var logTclosePrice = record.get('logTclosePrice');
		var currentPrice = value;
		if (currentPrice > logTclosePrice) {
			metaData.tdStyle = 'background-color:red; color: white';
		} else if (currentPrice < logTclosePrice) {
			metaData.tdStyle = 'background-color:green; color: white';
		}
		return Ext.util.Format.number(value, '￥0.00')
	},

	updateSort: function () {
		var store = this.getView().store, details = [], vm = this.getViewModel();
		store.getSorters().each(function (sorter) {
			details.push(sorter.getProperty() + ' ' + sorter.getDirection());
		});
		console.debug('details', details);
		// vm.set({
		// 	sortOrder: details.join(', ')
		// });
	},
	/**
	 * 查看增长日志, 弹窗样式
	 */
	popupLogWin: function (id, slimsymbol, stkname, grade) {
		//console.debug('超链进来了', { id, slimsymbol, stkname, grade });
		var popWin = Ext.widget("window", {
			title: '查看日志',
			layout: 'fit',
			width: 1450,
			height: 750,
			minWidth: 600,
			minHeight: 500,
			border: false,
			plain: true,
			modal: true,
			resizable: true,
			items: [{ xtype: "stockor.statist.buyinpoint.form.BuyinPointLogGrid" }]
		});
		var popWinPanel = popWin.getComponent(0); //获取form view
		var popWinViewModel = popWinPanel.getViewModel(); //获取view的viewmodel
		popWinViewModel.set('buyinPoint.id', id);
		popWinViewModel.set('buyinPoint.slimsymbol', slimsymbol);
		popWinViewModel.set('buyinPoint.stkname', stkname);
		popWinViewModel.set('buyinPoint.grade', grade);

		this.getView().add(popWin);
		popWin.show();

		//设置加载窗口的数据源
		popWinViewModel.getStore('buyinPointLogStore').load({
			params: { parentid: id }
		});
		var winheight = popWin.getHeight(); //获取初始化后窗口的宽度
		var winwidth = popWin.getWidth(); //获取初始化后窗口的高度
		if (winheight - 10 > screenY) { //判断窗口高度是否小于浏览器的窗口高度(留有10px的余量)
			popWin.setHeight(screenY - 30); //设置高度适应浏览器高度(底部留有30px余量，顶部还有10px)
			popWin.setWidth(winwidth + 30); //因为出现了滚动条，增加显示滚动条的宽度
		}
	},

	/**
	 * 查看增长日志, Tab样式
	 */
	onBtnBuyPointLogClick: function (btn) {
		console.debug('底部工具条查看查看增长日志按钮事件');
		var myview = this.getView();
		var selRec = this._getSingleSelRec(myview.getSelectionModel().getSelection());
		if (!selRec) {
			return;
		}
		var pid = selRec.get('id');
		var slimsymbol = selRec.get('slimsymbol');
		var stkname = selRec.get('name');
		var grade = selRec.get('grade');
		/**
		 * 这里之前是弹出一个带有symbol id的tab，现在的单页显示模式下， 需要完成一个弹出浏览器新窗口的操作，然后用Ext.window.Window的形式全页展示
		 */
		// console.debug('1 window.location:', window.location);
		// console.debug('1 window.location.origin:', window.location.origin);
		// console.debug('1 window.location.pathname:', window.location.pathname);
		// console.debug('1 window.location.search:', window.location.search);


		new_window_url = '' + window.location.origin + '?classic&id=' + pid + '&slimsymbol=' + slimsymbol + '&stkname=' + stkname + '&grade=' + grade + '#buyin-point-log-window'
		console.debug('new_window_url:', new_window_url);
		window.open(new_window_url);

	},
	onBtnCloseClick: function () {
		console.debug('底部工具条关闭按钮事件');
		var myview = this.getView();
		var myviewmodel = myview.getViewModel();
		var selRec = this._getSingleSelRec(myview.getSelectionModel().getSelection());
		if (!selRec) {
			return;
		}
		var status = selRec.get('status');
		if (status === 'CLOSE') {
			Ext.MessageBox.alert('提示', '只能关闭非CLOSE状态买点');
			return;
		} else {
			Ext.MessageBox.alert('提示', '功能实现中, 敬请期待...');
			return;
		}
	},
	/**
	 * 查看各级标准K线图, Tab样式
	 */
	onBtnKlineChartClick: function (btn) {
		var klinetype;
		if (btn.klinetype) {
			klinetype = btn.klinetype;
		} else {
			klinetype = 'standard';
		}
		var myview = this.getView();
		var selRec = this._getSingleSelRec(myview.getSelectionModel().getSelection());
		if (!selRec) {
			return;
		}
		var slimsymbol = selRec.get('slimsymbol');
		var stkname = selRec.get('name');
		var grade = selRec.get('grade');
		new_window_url = '' + window.location.origin
			+ '?classic&klinetype=' + klinetype + '&slimsymbol=' + slimsymbol + '&stkname=' + stkname
			+ '&grade=' + grade + '&isMacdDisplayed=' + 'true'
			+ '&_dc=' + new Date().getTime() + '#kline-window'
		console.debug('new_window_url:', new_window_url);
		window.open(new_window_url);
	},
	/**
	 * 判断选择记录条数, 只允许一条, 返回选择记录的id
	 */
	_getSingleSelRec: function (selRecords) {
		if (selRecords.length == 0) {
			Ext.MessageBox.alert('信息提示', '请选择需要操作数据!');
			return null;
		}
		if (selRecords.length > 1) {
			Ext.MessageBox.alert('信息提示', '只能选择一条数据操作!');
			return null;
		}
		return selRecords[0];
	},
	/**
	 * 弹窗显示实时价格加入K线后的买入点分析
	 * cell内的超链点击响应函数
	 */
	realtimeBuyinPointAnalyze: function (btn, slimsymbol, stkname, grade) {
		var myview = this.getView();
		var myviewmodel = myview.getViewModel();
		var buyinPointStore = myviewmodel.getStore('buyinPointStore');
		var params = [];
		if (btn == null) {
			//console.debug('realtimeBuyinPointAnalyze 超链进入-btn', btn);
			params.push(slimsymbol + '-' + grade);
		} else {
			//console.debug('realtimeBuyinPointAnalyze 底部工具栏多选按钮进入');
			var selRec = myview.getSelectionModel().getSelection();
			if (selRec.length == 0) {
				Ext.MessageBox.alert('信息提示', '请选择需要操作数据!');
				return;
			}
			for (var i = 0; i < selRec.length; i++) {
				params.push(selRec[i].get('slimsymbol') + '-' + selRec[i].get('grade'));
			}
		}
		//
		Ext.Ajax.request({
			url: BizHttpAction.fetchMultiCurrentPrice2BuyinAnalyze.url,
			method: BizHttpAction.fetchMultiCurrentPrice2BuyinAnalyze.method,
			params: {
				'slimsymbolGrades': params.join(','),
				'viaProxy': 'false'
			},
			disableCaching: false,
			success: function (response, opts) {
				var respJson = Ext.JSON.decode(response.responseText);
				if (respJson.success != true) {
					Ext.MessageBox.alert('提示', respJson.message);
					return;
				}
				var respDataArray = respJson.data;
				if (respDataArray == null) {
					Ext.MessageBox.alert("提示", '没有买入点结果');
					return;
				}

				if (respDataArray) {
					for (i = 0; i < respDataArray.length; i++) {
						var respData = respDataArray[i];
						//console.debug('respData idx=' + i, respData);
						var myrecord = buyinPointStore.findRecord('slimsymbol', respData.slimsymbol);
						//
						if (myrecord) {
							//console.debug('找到本地的记录:', myrecord);
							myrecord.set('realtimeStatus', respData.status);
							myrecord.set('realtimeInfoTime', respData.infoTime);
							myrecord.set('realtimeTopenPrice', respData.topenPrice);
							myrecord.set('realtimeTclosePrice', respData.tclosePrice);
							myrecord.set('realtimeThighPrice', respData.thighPrice);
							myrecord.set('realtimeTlowPrice', respData.tlowPrice);
							myrecord.set('realtimetCloseIncreaseAmount', respData.tcloseIncreaseAmount);
							myrecord.set('realtimetCloseProfitRatio', respData.tcloseProfitRatio);
							myrecord.set('realtimeBackoff34TermsIslowest', respData.backoff34TermsIslowest);
							myrecord.set('realtimeBackoff55TermsIslowest', respData.backoff55TermsIslowest);
							myrecord.set('realtimeBackoff89TermsIslowest', respData.backoff89TermsIslowest);
							myrecord.set('realtimeBackoff144TermsIslowest', respData.backoff144TermsIslowest);
							myrecord.set('currentTime', respData.currentTime);
							myrecord.set('currentPrice', respData.currentPrice);
							myrecord.set('currentOpen', respData.currentOpen);
							myrecord.set('currentHigh', respData.currentHigh);
							myrecord.set('currentLow', respData.currentLow);
							myrecord.commit();
						}
					}
				}
				// 暂时不再弹窗
				// var popWin = Ext.widget("window", {
				// 	title: '查看现价买入分析',
				// 	layout: 'fit',
				// 	width: 850,
				// 	height: 600,
				// 	minWidth: 600,
				// 	minHeight: 500,
				// 	border: false,
				// 	plain: true,
				// 	modal: false,
				// 	resizable: true,
				// 	items: [{ xtype: "stockor.statist.form.RealtimeBuyinPointForm" }]
				// });
				// var popWinPanel = popWin.getComponent(0); //获取form view
				// var popWinViewModel = popWinPanel.getViewModel(); //获取view的viewmodel
				// popWinViewModel.set('realtimeBuyinPoint', respJson.data);
				// //popWinViewModel.set('realtimeBuyinPoint.name', selRec.get('name'));

				// Ext.getCmp('main-tab-panel').getActiveTab().add(popWin); //每个tab有各自模式window
				// //view.up().add(formAddwin); //每个tab有各自模式window
				// popWin.show();

				// var winheight = popWin.getHeight(); //获取初始化后窗口的宽度
				// var winwidth = popWin.getWidth(); //获取初始化后窗口的高度
				// if (winheight - 10 > screenY) { //判断窗口高度是否小于浏览器的窗口高度(留有10px的余量)
				// 	popWin.setHeight(screenY - 30); //设置高度适应浏览器高度(底部留有30px余量，顶部还有10px)
				// 	popWin.setWidth(winwidth + 30); //因为出现了滚动条，增加显示滚动条的宽度
				// }
			},
			failure: function (response, opts) {
				var respJson = Ext.JSON.decode(response.responseText);
				Ext.MessageBox.alert("提示", respJson.message);
			}
		});
	}
});